import * as crypto from "crypto"
import * as Sign from "@litert/signatures"
export class Crypto {
    //签名
    sign(data: any, privateKey: string) {

       try {
        delete data.signature;
        console.log(data);

        const prv = this.exportPrvDer(privateKey);
    
        let msg = JSON.stringify(data);
        //创建签名实例
        
        let sign=crypto.createSign("SHA256");
        sign.update(msg)
        console.log(prv);
        const ecdsaSign = sign.sign(prv,"base64")  // Sign.ECDSA.sign("sha256", msg, { key: prv, password: '' })

        console.log(prv)
        console.log("签名")
        console.log(ecdsaSign)
        console.log("msg",msg)
        return ecdsaSign
       } catch (error) {
           console.log(error.toString())
       }

    }
    //验签
    verfiy(data: any, publicKey: string, signature: any) {
     
        
        const verify = crypto.createVerify('SHA256');

        delete data.signature;
        let msg = JSON.stringify(data);
        
        const pub = Buffer.from(publicKey, "base64").toString("ascii");

        console.log(pub)

        console.log(signature)
        
        verify.update(msg);

        const n = verify.verify(pub,signature) //Sign.ECDSA.verify("sha256", msg, signature, pub)
        console.log(n);
    }
    //导出der
    exportPubDer(pem:string){
     const key = Buffer.from(pem, "base64").toString("ascii");
     let pub=crypto.createPublicKey(key);
     let pubder=pub.export({type:"spki",format:"der"})
     console.log(pubder.toString("base64"))
     return pubder.toString("base64")
    }
    
    exportPrvDer(pem:string){
        console.log("prv")
        const key = Buffer.from(pem, "base64").toString("ascii");
        console.log(key)
        let pub=crypto.createPrivateKey(key);
        return pub
    }
}